package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.校验参数
        String phone = dto.getPhone();
        String password = dto.getPassword();
        //判断手机号密码是否为空
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(password)) {
            //如果不为空使用手机号+密码登录
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, phone));
            //判断是否查询到
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在！");
            }
            // 数据库密码
            // 对比输入密码和数据库密码是否一致
            String inputPassword = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!inputPassword.equals(apUser.getPassword())) {
               CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户密码错误！");
            }
            //颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //返回结果
            Map result=new HashMap<>();
            result.put("token",token);
            apUser.setSalt("");
            apUser.setPassword("");
            result.put("user",apUser);
            return ResponseResult.okResult(result);
        } else {
            //使用设备id登录  判断设备id是否为空
            if (dto.getEquipmentId() == null) {
               CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未发现设备id，参数异常！");
            }
            //颁发token  通过设备ID登录的 userId存0
            String token = AppJwtUtil.getToken(0L);
            //返回结果
            Map result=new HashMap<>();
            result.put("token",token);
            return ResponseResult.okResult(result);
        }
    }
}
